/*
 * These files are distributed under the terms of the GNU GPLv2, the GNU General
 * Public version 2. See LICENSE.txt
 */
package fileCommodore.plugin.usermenu;

import java.awt.event.*;
import java.io.*;
import java.util.*;

import javax.swing.*;

import fileCommodore.plugin.*;

public class UserMenuPlugin extends Plugin {

	private EntryListModel model;
	private ActionListener entryLauncher = new ActionListener(){
		public void actionPerformed(ActionEvent ev) {
			MenuEntry me = (MenuEntry) ev.getSource();
			Entry e = me.getEntry();
			
			// Add a place-holder for the program path
			String[] command = ("$(program) " + e.getArguments()).split("\\s");
			command[0] = e.getProgram();
			
			File currentDir = new File(getActiveSelection().getCurrent().getFileObject().getName().getPath() );
			boolean useShell = EntryType.NoShell != e.getType() && EntryType.NoShellCapture != e.getType();

			Vector<Process> result = substituteAndLaunch( currentDir, command, useShell );
			
			if( EntryType.NoShellCapture == e.getType() )
			{
				StringBuffer sb = new StringBuffer();
				try {
					Process firstProcess = result.get(0);
					int exitCode = firstProcess.waitFor();
					BufferedReader br = new BufferedReader(new InputStreamReader(firstProcess.getInputStream()));
					for(;;)
					{
						String line = br.readLine();
						if( null == line )
						{
							break;
						}
						sb.append(line);
					}
				} catch (IOException ex) {
					// TODO Auto-generated catch block
					ex.printStackTrace();
				} catch (InterruptedException ex) {
					// TODO Auto-generated catch block
					ex.printStackTrace();
				}

				if( sb.length() > 0 )
				{
					JFrame f = new JFrame("Command Output");
					JTextArea ta = new JTextArea(sb.toString());
					ta.setEditable(false);
					JScrollPane sp = new JScrollPane(ta);
					f.setContentPane(sp);
					f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
					f.setLocationByPlatform(true);
					f.pack();
					f.setVisible(true);
				}
				
				if( result.size() > 1 )
				{
					showWarning("Multiple Processes", "Multiple commands were executed, but only showing output for the first one.");
				}
			}
		}
	};
	
	private EntryListModel getModel()
	{
		if( null == model )
		{
			model = EntryListModel.deserialize(getProperty("user-menu-entries"));
		}
		
		return model;
	}
	
	@Override
	public void activeSelectionChanged() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void handle(KeyEvent ev) {
		if( KeyEvent.VK_F9==ev.getKeyCode() || (isAltDown(ev) && KeyEvent.VK_SLASH==ev.getKeyCode()) )
		{
			JPopupMenu m = new JPopupMenu("User Menu");
			for(int i=0; i<getModel().getSize(); i++)
			{
				Entry e = (Entry) getModel().getElementAt(i);
				MenuEntry me = new MenuEntry(e);
				me.addActionListener(entryLauncher);
				m.add(me);
			}
			m.addSeparator();
			JMenuItem customize = new JMenuItem("Customize...");
			m.add(customize);
			customize.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					Editor ed = new Editor(getDialogParent(), getModel());
					if( ed.shouldSave() )
					{
						setProperty("user-menu-entries", getModel().serialize());
					}
				}
			});
			show(m);
		}
	}

	@Override
	public void inactiveSelectionChanged() {
		// TODO Auto-generated method stub
		
	}

}
